
const fs = require('fs');
const readline = require('readline');
const Kook = require('./kook');
const Minecraft = require('./minecraft');
const target_id = "2798438992367198";
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

class KookBot extends Kook {

    constructor(token, client_id, McConfig) {
        super(token, client_id);
        this.transmitArr = [];
        let userInfo = JSON.parse(fs.readFileSync('userInfo.json', 'utf8'));
        this.mc = new Minecraft(McConfig, userInfo);
        this.userInfo = userInfo[0];
    };

    async connectWebSocket() {
        super.connectWebSocket(this.msgParse.bind(this));
    }

    async msgParse(data) {
        // console.log("DATA: " + JSON.stringify(data));
        if(data.type == 10) return;
        const tokens = data.content.trim().split(' ');
        const guild_id = data.extra.guild_id;
        const target_id = data.target_id;
        const user_id = data.author_id;

        let index = this.transmitArr.indexOf(target_id);
        let command = tokens[1];
        let content = tokens.slice(2).join(' ');

        if (tokens[0] != '(met)1598039734(met)') {
            if (index === -1) return;
            const user_name = data.extra.author.username;
            let format = this.getTellrawFormat(data.content, user_name, user_id);
            this.mc.tellraw(format.msg, format.color, format.is_bold);
            return;
        };

        console.log(`TID:${target_id}\nUID:${user_id}\nCMD:${command}`);

        switch (command) {
            case '帮助':
                this.sendMsg("还没写 哈哈", target_id);
                break;
            case '状态':
                this.sendMsg(`Kook\t->\tMC\t\t${(this.index && this.index === -1) ? "❎" : "✅"}\nMC\t\t->\tKook\t${this.mc.client ? "✅" : "❎"}`, target_id);
                break;
            case '开始同步':
                if (index !== -1) {
                    this.sendMsg("别叫了 发着呢😡", target_id);
                    return;
                };
                this.mc.connectWebSocket(target_id, this.sendCardMsg.bind(this))
                    .catch(err=>console.log(err));
                this.transmitArr.push(target_id);
                this.sendMsg("懂了", target_id);
                break;
            case '停止同步':
                if (index === -1) {
                    this.sendMsg("别叫了 跟没转发😡", target_id);
                    return;
                };
                if (this.mc.client) {
                    this.mc.stop();
                };
                this.transmitArr.splice(index, 1);
                this.sendMsg("懂了", target_id);
            case "绑定":

            default:
                break;
        }
        return;
    };

    getTellrawFormat(msg, user_name, user_id){
        let format = {};
        if(this.userInfo[user_id]){
            let info = this.userInfo[user_id];
            if (info.title) format.msg = `[${info.title}] `;
            format.msg += `<${info.name}>`;
            format.color = info.color;
            format.is_bold = info.is_bold;
        }else{
            format.msg = `<${user_name}>`;
        };
        if(msg.indexOf('(met)') !== -1){
            for(let id in this.userInfo){
                msg = msg.replace(`(met)${id}(met)`, "@"+this.userInfo[id].name);
            };
        };
        format.msg += `: ${msg}`;
        return format;
    }
}


const { FuyuSecret, ListenerConfig , McConfig} = JSON.parse(fs.readFileSync('./APIconfig.json', 'utf8'));
const latestID = fs.readFileSync('./latestID.txt', 'utf8');
const client = new KookBot(ListenerConfig.token, ListenerConfig.client_id, McConfig);

rl.on('line', (input) => {
    switch(input){
        case 'exit':
            rl.close();
            break;
        case "poll":
            console.log(mc.polling);
    };
});
rl.on('close', async () => {
    if (client) {
        client.exit = true;
        await client.sendMsg("What can I say?\nListener Out😭", target_id);
        await client.offLine();
    };
    if (client.wsClient) await client.wsClient.close();
    if (client.mc.polling) {
        client.mc.off = true;
        await client.mc.stopFetchMsg();
    };
    process.exit();
});



try{
    client.connectWebSocket();
}catch(err){
    console.log(err);
}
